package com.xjtu.mybatisplus.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjtu.mybatisplus.common.result.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xjtu.mybatisplus.common.constant.JwtClaimsConstant;
import com.xjtu.mybatisplus.common.constant.MessageConstant;
import com.xjtu.mybatisplus.common.constant.PasswordConstant;
import com.xjtu.mybatisplus.common.exception.PasswordErrorException;
import com.xjtu.mybatisplus.common.properties.JwtProperties;
import com.xjtu.mybatisplus.common.utls.JwtUtil;
import com.xjtu.mybatisplus.model.domain.Role;
import com.xjtu.mybatisplus.model.domain.User;
import com.xjtu.mybatisplus.mapper.UserMapper;
import com.xjtu.mybatisplus.model.dto.adminDto.PageInfoDto;
import com.xjtu.mybatisplus.model.vo.adminVo.UserVo;
import com.xjtu.mybatisplus.model.dto.UserLoginDto;
import com.xjtu.mybatisplus.model.vo.UserLoginVo;
import com.xjtu.mybatisplus.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjtu.mybatisplus.web.controller.UserController;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lsong
 * @since 2023-12-27
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired(required = false)
    private UserMapper userMapper;

    private final Logger logger = LoggerFactory.getLogger( UserServiceImpl.class );
    @Override
    public PageResult getUsers(PageInfoDto pageInfoDto) {
        logger.info("获取到的数据{}",pageInfoDto);
        Page<UserVo> page = new Page<>(pageInfoDto.getPage(),pageInfoDto.getSize());
        userMapper.queryPage(page,pageInfoDto.getContent());
        List<UserVo> records = page.getRecords();
        PageResult pageResult = new PageResult();
        pageResult.setItems(records);
        pageResult.setTotal(page.getTotal());
        return pageResult;
    }

    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public UserLoginVo userLogin(UserLoginDto userLoginDto) {
//        User user = new User();
//        user.setUsername(userLoginDto.getUsername());
//        user.setPassword(userLoginDto.getPassword());

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        String username = userLoginDto.getUsername();
        String password = DigestUtils.md5DigestAsHex((userLoginDto.getPassword()+ PasswordConstant.SALT).getBytes());
        userQueryWrapper.eq("username", username).eq("password", password);
        System.out.println("用户名:" + username +" 密码:"+ password);
        List<User> users = userMapper.selectList(userQueryWrapper);
        if(users.size() == 0) {
            log.info("用户名或密码错误");
            return null;
        }

        User user = users.get(0);
        log.info("用户信息为：{}", user);
//        String passwordIn = DigestUtils.md5DigestAsHex((user.getPassword()+ PasswordConstant.SALT).getBytes());
//        if (!passwordIn.equals(user.getPassword())) {
//            //密码错误
//            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
//        }

        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        // 返回值

        Long type = userMapper.getUserRole(user.getId());
        System.out.println("type:" + type);
        UserLoginVo userLoginVo = UserLoginVo.builder()
                .id(user.getId())
                .username(user.getUsername())
                .token(token)
                .phone(user.getPhone())
                .sex(user.getSex())
                .mail(user.getEmail())
                .avator(user.getAvator())
                .type(type)
                .build();
        return userLoginVo;
    }

    @Override
    public UserLoginVo adminLogin(UserLoginDto userLoginDto) {

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        String username = userLoginDto.getUsername();
        String password = userLoginDto.getPassword() + PasswordConstant.SALT;
        userQueryWrapper.eq("username", username).eq("password", password);
        System.out.println("用户名:" + username +"/n 密码:"+ password);
        List<User> users = userMapper.selectList(userQueryWrapper);
        if(users.size() == 0) {
            log.info("用户名或密码错误");
            return null;
        }

        User user = users.get(0);
        Long type = userMapper.getUserRole(user.getId());
        System.out.println("type:" + type);
        if(type <= 1){
            log.info("普通用户");
            return null;
        }

        log.info("用户信息为：{}", user);
//        String passwordIn = DigestUtils.md5DigestAsHex((user.getPassword()+ PasswordConstant.SALT).getBytes());
//        if (!passwordIn.equals(user.getPassword())) {
//            //密码错误
//            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
//        }

        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        // 返回值



        UserLoginVo userLoginVo = UserLoginVo.builder()
                .id(user.getId())
                .username(user.getUsername())
                .token(token)
                .type(type)
                .build();
        return userLoginVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User create(User user) {
        if(userMapper.insert(user) > 0) {
            userMapper.insertRole(user.getId());
            return user;
        }
        return null;
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public Result<User> delete(User user) {
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(User::getUsername, user.getUsername());
//        return userMapper.delete(queryWrapper) > 0 ? new Result<User>().ok(user) : new Result<User>().error("删除用户失败");
//    }
//
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public Result<User> update(User user) {
//        return userMapper.updateById(user) > 0 ? new Result<User>().ok(user) : new Result<User>().error("更新用户失败");
//    }

    @Override
    public User findByUserName(String userName) {
        return userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUsername, userName));
    }

    @Override
    public boolean registerEmailExist(String email) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getEmail, email);
        return userMapper.selectOne(queryWrapper) != null;
    }

    @Override
    public boolean updateByUserEmail(String email) {
         return userMapper.updateByEmail(email) > 0;
    }

}
